package com.ruoyi.common.utils;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.DateUtil;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        if(date == null){
            return "";
        }
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }



    /**
     * 计算两个时间 之间的天数
     */
    public static int getDaysCountBetween2Date(Date startDate, Date endDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff =  endDate.getTime() - startDate.getTime() ;
        // 计算差多少天
        long day = diff / nd;

        // long 转换为 int

        return (int) day;
    }



    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 指定日期按指定格式显示
     *
     * @param date    指定的日期
     * @param pattern 指定的格式
     * @return 指定日期按指定格式显示
     */
    public static String formatDate(Date date, String pattern) {
        if(date == null){
            return "无";
        }
        return getSDFormat(pattern).format(date);
    }

    // 指定模式的时间格式
    private static SimpleDateFormat getSDFormat(String pattern) {
        return new SimpleDateFormat(pattern);
    }

    public static Date getNextDate(Date date){
        if(date == null){
            date = new Date();
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        // 把日期往后增加一天,整数  往后推,负数往前移动
        calendar.add(Calendar.DATE, 1);
        // 这个时间就是日期往后推一天的结果
        date = calendar.getTime();
        return date;
    }

    /**
     * 获取最近7天
     * @param days
     * @return
     */
    public static List<String> getSevenDate(Integer days){
        List<String> dateList = new ArrayList<>();

        if(days == null){
            days = 7;
        }
        for (int i = 0; i < days; i++) {
            Date date = DateUtils.addDays(new Date(), -i);
            String formatDate = dateTime(date);
            dateList.add(formatDate);
        }
        return dateList;
    }

    public static void main(String[] args) {
        List<String> data = getSevenDate(7);
        System.out.println(data);
    }

    public static Boolean  isWithinCurrentRange(Date dateParam, String type){
        Boolean res = true;
        Date today = new Date();
        LocalDate localToday = dateToLocalDate(today);
        LocalDate paramDate = dateToLocalDate(dateParam);
        if("yestoday".equals(type)){
            res =  DateUtils.isSameDay(dateParam, addDays(new Date(), -1));
        }else if("today".equals(type)){
            res =  DateUtils.isSameDay(dateParam, new Date());
        }else if("week".equals(type)){
            Long startOfWeek = getStartOfWeek(paramDate);
            Long endOfWeek = getEndOfWeek(paramDate);
            res = (localToday.toEpochDay() >= startOfWeek) && (localToday.toEpochDay() <= endOfWeek);
        }else if("month".equals(type)){
            LocalDate startOfMonth = paramDate.with(TemporalAdjusters.firstDayOfMonth()); // 获取本月的开始时间
            LocalDate endOfMonth = paramDate.with(TemporalAdjusters.lastDayOfMonth()); // 获取本月的结束时间
            res = (localToday.compareTo(startOfMonth) > -1) && (localToday.compareTo(endOfMonth) < 1);
        }else if("season".equals(type)){
            int month = paramDate.getMonthValue(); // 获取季度所属月份
            int paramQuarter = (month - 1) / 3 + 1; // 计算数据所属季度
            LocalDate localDate = LocalDate.now();
            int localMonth = localDate.getMonthValue(); // 获取当前月份
            int localQuarter = (localMonth - 1) / 3 + 1; // 计算当前季度
            if(paramQuarter == localQuarter){
                res = true;
            }else{
                res = false;
            }
        }
        return res;
    }
    public static long getStartOfWeek(LocalDate date) {
        return date.minusDays(date.get(ChronoField.DAY_OF_WEEK) % 7).toEpochDay();
    }

    public static long getEndOfWeek(LocalDate date) {
        return date.plusDays(6 - date.get(ChronoField.DAY_OF_WEEK) % 7).toEpochDay();
    }

    public static LocalDate dateToLocalDate(Date date){
        LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        return localDate;
    }

    public static Boolean  isWithinDayRange(Date dateParam, int beg, int end){
        Boolean res = true;
        int days = differentDaysByMillisecond(dateParam, new Date());
        if(days >=beg && days < end){
            res = true;
        }else{
            res = false;
        }
        return res;
    }


    public static Date getDateFromExcel(String date) {
        if (StringUtils.isNotBlank(date)) {
            try {
                Pattern pattern = Pattern.compile("[0-9]+[.]{0,1}[0-9]*[dD]{0,1}");
                Matcher isNum = pattern.matcher(date);
                if (!isNum.matches()) {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    return df.parse(date);
                } else {
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    String dates = df.format(DateUtil.getJavaDate(Double.parseDouble(date)));
                    return DateUtils.parseDate(dates, "yyyy-MM-dd");
                }
            } catch (Exception e) {
                return null;
            }
        }
        return null;




    }

}
